package com.ulook.lookplanet.ui.square.article;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.qmuiteam.qmui.layout.QMUIFrameLayout;
import com.qmuiteam.qmui.skin.QMUISkinHelper;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.skin.QMUISkinValueBuilder;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIResHelper;
import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.popup.QMUIFullScreenPopup;
import com.qmuiteam.qmui.widget.popup.QMUIPopups;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.ulook.lookplanet.R;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.data.model.TArtPic;
import com.ulook.lookplanet.data.model.TTopic;
import com.ulook.lookplanet.ui.notifications.UserDetail.UserDetailActivity;
import com.ulook.lookplanet.ui.square.VArticlePreInfo;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.json.JacksonUtil;
import com.ulook.lookplanet.util.net.AsynRequestUtil;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.RequestParams;
import com.ulook.lookplanet.util.net.ResponseByteCallback;
import com.ulook.lookplanet.util.net.ResponseCallback;
import com.ulook.lookplanet.widget.AudioPlayerLayout;
import com.ulook.lookplanet.widget.CommentView;

import java.io.File;
import java.util.List;

public class  ArticleActivity extends AppCompatActivity {

    private ArticleViewModel viewModel;
    private int currUserId;
    private VArticlePreInfo articlePreInfo;
    private int imageWidth;

    private QMUIRadiusImageView2 userHeadImg;
    private QMUIFloatLayout topicLayout;
    private AudioPlayerLayout audioPlayerLayout;
    private QMUIFloatLayout imageLayout;
    private ImageButton likeBt;
    private TextView likeNum;
    private ImageButton collectBt;
    private TextView collectNum;
    private ImageButton commentBt;
    private TextView commentNum;
    private LinearLayout commentLayout;
    private CommentView myComment;
    private QMUIRoundButton moreBt;
    private QMUIFullScreenPopup popup;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article);

        viewModel = new ViewModelProvider(this).get(ArticleViewModel.class);
        viewModel.getToastText().observe(this, s -> {
            Toast.makeText(ArticleActivity.this, s, Toast.LENGTH_SHORT).show();
        });
        viewModel.getImages().observe(this, artPics -> {
            displayImage(artPics);
        });
        viewModel.getTopics().observe(this, topics -> {
            displayTopic(topics);
        });
        viewModel.getArtCount().observe(this, artCount -> {
            initCount(artCount);
        });
        viewModel.getCommentInfos().observe(this, commentInfos -> {
            displayComment(commentInfos);
        });
        viewModel.getMyComment().observe(this, commentInfo -> {
            showMyComment(commentInfo);
        });
        viewModel.getState().observe(this, commentState -> {
            commentStateChange(commentState);
        });

        Intent intent = getIntent();
        currUserId = intent.getIntExtra("currUserId", 0);
        viewModel.setCurrUserId(currUserId);
        articlePreInfo = (VArticlePreInfo) intent.getSerializableExtra("article");
        viewModel.setArticlePreInfo(articlePreInfo);

        initTopBar();
        initData();
    }

    private void initTopBar(){
        QMUITopBarLayout topBar = findViewById(R.id.article_bar);
        topBar.addLeftBackImageButton().setOnClickListener(view -> {
            finish();
        });
        topBar.setTitle("动态");
    }

    private void initData(){
        TextView authorName = findViewById(R.id.article_author_name_text);
        if(articlePreInfo.getName() != null){
            authorName.setText(articlePreInfo.getName());
        }
        TextView pubTime = findViewById(R.id.article_pub_time_text);
        if(articlePreInfo.getPubtime() != null){
            pubTime.setText(articlePreInfo.getPubtime().subSequence(5, 16));
        }
        TextView content = findViewById(R.id.article_content_text);
        if(articlePreInfo.getContent() != null){
            content.setText(articlePreInfo.getContent());
        }

        // 获取用户头像
        userHeadImg = findViewById(R.id.article_author_img);
        if(!(articlePreInfo.getHeadimg() == null || "".equals(articlePreInfo.getHeadimg()))){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
                    userHeadImg.setImageBitmap(bitmap);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.HEAD_IMG_PATH + articlePreInfo.getHeadimg(), null, callback);
        }
        userHeadImg.setClickable(true);
        userHeadImg.setOnClickListener(view -> {
            Intent intent = new Intent(ArticleActivity.this, UserDetailActivity.class);
            intent.putExtra("user", viewModel.getArticlePreInfo().getId());
            intent.putExtra("currUser", viewModel.getCurrUserId());
            startActivity(intent);
        });

        // 获取录音
        audioPlayerLayout = findViewById(R.id.w_art_audio_layout);
        if(!(articlePreInfo.getAudrofile() == null || "".equals(articlePreInfo.getAudrofile()))){
            String url = AppServer.AUDIO_PATH + articlePreInfo.getAudrofile();
            String dir = getExternalCacheDir() + File.separator;
            ResponseByteCallback callback = new ResponseByteCallback() {
                @Override
                public void onSuccess(File file) {
                    audioPlayerLayout.setMediaPath(dir + articlePreInfo.getAudrofile());
                    audioPlayerLayout.setVisibility(View.VISIBLE);
                }
                @Override
                public void onFailure(String failureMsg) {
                    ThrowException.print(failureMsg);
                }
            };
            AsynRequestUtil.postLoadImg(url, null, dir, articlePreInfo.getAudrofile(), callback);
        }

        // 获取话题
        topicLayout = findViewById(R.id.article_topic_layout);
        if(articlePreInfo.getHastopic() != 0){
            viewModel.getArtTopics(articlePreInfo.getUid());
        }

        // 获取图片
        imageLayout = findViewById(R.id.article_image_layout);
        if(articlePreInfo.getHaspic() != 0){
            viewModel.getPic(articlePreInfo.getUid());
        }

        // 获取统计数据
        viewModel.getCount(articlePreInfo.getUid());

        // 设置点赞收藏
        initLikeInfo();

        // 评论
        initComment();

    }

    /**
     * 获取话题
     */
    private void displayTopic(List<TTopic> topics){
        if(topics != null){
            for(TTopic tTopic : topics){
                TextView textView = new TextView(ArticleActivity.this);
                textView.setText(tTopic.getName());
                textView.setTextColor((ArticleActivity.this).getResources().getColor(R.color.light_blue_600));
                topicLayout.addView(textView);
            }
        }

    }

    /**
     * 获取统计数据
     */
    private void initCount(VArtCount artCount){
        likeNum = findViewById(R.id.article_like_num);
        likeNum.setText(String.valueOf(artCount.getLikeNum()));
        collectNum = findViewById(R.id.article_collcet_num);
        collectNum.setText(String.valueOf(artCount.getCollectNum()));
        commentNum = findViewById(R.id.article_comment_num);
        commentNum.setText(String.valueOf(artCount.getCommentNum()));
    }

    /**
     * 评论
     */
    private void initComment(){
        // 设置评论按钮
        commentBt = findViewById(R.id.article_comment_bt);
        myComment = findViewById(R.id.article_my_comment);
        // 点击评论
        commentBt.setOnClickListener(view -> {
            replayAction(view);
        });
        // 获取品论数据
        viewModel.getComment(0);

        // 更多
        moreBt = findViewById(R.id.article_more_comment_bt);
        moreBt.setOnClickListener(view -> {
            int itemNum = commentLayout.getChildCount();
            viewModel.getComment(itemNum);
        });
    }



    /**
     * 设置点赞收藏
     */
    private void initLikeInfo(){
        // 点赞
        likeBt = findViewById(R.id.article_like_bt);
        if(articlePreInfo.getIslike() != null && !"".equals(articlePreInfo.getIslike())){
            likeBt.setImageResource(R.drawable.ic_like_red);
        }else {
            likeBt.setImageResource(R.drawable.ic_like_white);
        }
        likeBt.setOnClickListener(view -> {
            if(currUserId != 0){
                RequestParams params = new RequestParams();
                params.put("userid", articlePreInfo.getId());
                params.put("artid", articlePreInfo.getUid());
                if(articlePreInfo.getIslike() == null || "".equals(articlePreInfo.getIslike())){
                    likeBt.setImageResource(R.drawable.ic_like_red);
                    articlePreInfo.setIslike("1");
                    likeNum.setText(String.valueOf(Integer.parseInt(likeNum.getText().toString())+1));
                }else {
                    likeBt.setImageResource(R.drawable.ic_like_white);
                    articlePreInfo.setIslike(null);
                    likeNum.setText(String.valueOf(Integer.parseInt(likeNum.getText().toString())-1));
                    params.put("isCancel", "1");
                }
                AsynRequestUtil.post(AppServer.ROOT_PATH+"/article/like", params, null, null);
            }else {
                Toast.makeText(ArticleActivity.this, "未登录用户", Toast.LENGTH_SHORT).show();
            }

        });
        // 收藏
        collectBt = findViewById(R.id.article_collect_bt);
        if(articlePreInfo.getIscollect() != null && !"".equals(articlePreInfo.getIscollect())){
            collectBt.setImageResource(R.drawable.ic_collection_yellor);
        }else {
            collectBt.setImageResource(R.drawable.ic_collection_white);
        }
        collectBt.setOnClickListener(view -> {
            if(currUserId != 0){
                RequestParams params = new RequestParams();
                params.put("userid", articlePreInfo.getId());
                params.put("artid", articlePreInfo.getUid());
                if(articlePreInfo.getIscollect() == null || "".equals(articlePreInfo.getIscollect())){
                    collectBt.setImageResource(R.drawable.ic_collection_yellor);
                    articlePreInfo.setIscollect("1");
                    collectNum.setText(String.valueOf(Integer.parseInt(collectNum.getText().toString())+1));
                }else {
                    collectBt.setImageResource(R.drawable.ic_collection_white);
                    articlePreInfo.setIscollect(null);
                    collectNum.setText(String.valueOf(Integer.parseInt(collectNum.getText().toString())-1));
                    params.put("isCancel", "1");
                }
                AsynRequestUtil.post(AppServer.ROOT_PATH+"/article/collect", params, null, null);
            }else {
                Toast.makeText(ArticleActivity.this, "未登录用户", Toast.LENGTH_SHORT).show();
            }

        });

    }

    /**
     * 展示图片
     */
    private void displayImage(List<TArtPic> artPics){
        imageLayout.removeAllViews();
        if(artPics == null){
            return;
        }
        int width = imageLayout.getWidth();
        int size = artPics.size();
        if(size == 1){
            imageWidth = width;
        }else if (size == 2 || size == 4){
            imageWidth = (width - 2) / 2;
        }else {
            imageWidth = (width -2) / 3;
        }
        for(int i = 0; i < size; i++){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  //使用BitmapFactory工厂，把字节数组转化为bitmap
                    ImageView imageView = new ImageView(ArticleActivity.this);
                    imageView.setImageBitmap(bitmap);
                    GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
                    layoutParams.width = imageWidth;
                    layoutParams.height = imageWidth;
                    imageView.setLayoutParams(layoutParams);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageLayout.addView(imageView);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.ARTICLE_IMG_PATH + artPics.get(i).getUid(), null, callback);
        }
    }

    /**
     * 点击评论动作
     * @param view
     */
    private void replayAction(View view){
        QMUISkinValueBuilder builder = QMUISkinValueBuilder.acquire();

        final FrameLayout editFitSystemWindowWrapped = new FrameLayout(ArticleActivity.this);
        editFitSystemWindowWrapped.setFitsSystemWindows(true);
        //QMUIWindowInsetHelper.handleWindowInsets(editFitSystemWindowWrapped, WindowInsetsCompat.Type.navigationBars() | WindowInsetsCompat.Type.displayCutout(), true);
        //QMUIKeyboardHelper.listenKeyBoardWithOffsetSelf(editFitSystemWindowWrapped, true);

        int minHeight = QMUIDisplayHelper.dp2px(ArticleActivity.this, 48);
        QMUIFrameLayout editParent = new QMUIFrameLayout(ArticleActivity.this);
        editParent.setMinimumHeight(minHeight);
        editParent.setRadius(minHeight / 2);
        editParent.setBackground(QMUIResHelper.getAttrDrawable(ArticleActivity.this, R.attr.qmui_skin_support_popup_bg));
        builder.clear();
        builder.background(R.attr.qmui_skin_support_popup_bg);
        QMUISkinHelper.setSkinValue(editParent, builder);

        // 输入框
        EditText editText = new EditText(ArticleActivity.this);
        editText.setHint("请输入...");
        editText.setBackground(null);
        builder.clear();
        QMUISkinHelper.setSkinValue(editText, builder);
        int paddingHor = QMUIDisplayHelper.dp2px(ArticleActivity.this, 20);
        int paddingVer = QMUIDisplayHelper.dp2px(ArticleActivity.this, 10);
        editText.setPadding(paddingHor, paddingVer, paddingHor, paddingVer);
        editText.setMaxHeight(QMUIDisplayHelper.dp2px(ArticleActivity.this, 100));
        // 回车键确认
        editText.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                    //Log.d("comment", "null---------"+(view instanceof CommentView));
                    if(view instanceof CommentView){
                        //Log.d("comment", ((CommentView)view).getCommentInfo().toString());
                        replayActionDown(((EditText)v).getText().toString().trim(), ((CommentView)view).getCommentInfo());
                    }else {
                        //Log.d("comment", "null---------");
                        replayActionDown(((EditText)v).getText().toString().trim(), null);
                    }
                    popup.dismiss();
                    return true;
                }
                return false;
            }
        });

        FrameLayout.LayoutParams editLp = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        editLp.gravity = Gravity.CENTER_HORIZONTAL;
        editParent.addView(editText, editLp);
        editFitSystemWindowWrapped.addView(editParent,  new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));

        ConstraintLayout.LayoutParams eLp = new ConstraintLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT);
        int mar = QMUIDisplayHelper.dp2px(ArticleActivity.this, 20);
        eLp.leftToLeft = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.rightToRight = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.bottomToBottom = ConstraintLayout.LayoutParams.PARENT_ID;
        eLp.leftMargin = mar;
        eLp.rightMargin = mar;
        eLp.bottomMargin = mar;

        popup = QMUIPopups.fullScreenPopup(ArticleActivity.this)
                .addView(editFitSystemWindowWrapped, eLp)
                .skinManager(QMUISkinManager.defaultInstance(ArticleActivity.this))
                .onBlankClick(new QMUIFullScreenPopup.OnBlankClickListener() {
                    @Override
                    public void onBlankClick(QMUIFullScreenPopup popup) {
                        //点击到空白区域
                        popup.dismiss();
                    }
                })
                .onDismiss(new PopupWindow.OnDismissListener() {
                    @Override
                    public void onDismiss() {
                    }
                });
        popup.show(view);
    }

    /**
     * 提交评论
     */
    private void replayActionDown(String commentText, VCommentInfo commentInfo){
        viewModel.commentAction(commentText, commentInfo);
    }

    /**
     * 显示评论
     */
    private void displayComment(List<VCommentInfo> commentInfos){
        commentLayout = findViewById(R.id.article_comment_layout);
        for(int i = 0; i < commentInfos.size(); i++){
            CommentView commentView = new CommentView(this);
            commentView.setWidgetData(commentInfos.get(i), currUserId);
            // 点击回复
            commentView.setOnClickListener(view -> {
                replayAction(view);
            });
            commentLayout.addView(commentView);
        }
    }

    /**
     * 评论后显示我的评论
     */
    private void showMyComment(VCommentInfo commentInfo){
        myComment.setWidgetData(commentInfo, currUserId);
        myComment.setVisibility(View.VISIBLE);
        commentNum.setText(String.valueOf(Integer.parseInt(commentNum.getText().toString())+1));
    }

    /**
     * 读取评论状态
     */
    private void commentStateChange(CommentState commentState){
        if(commentState.isNoMore()){
            moreBt.setClickable(false);
            moreBt.setText(R.string.article_no_more_comment);
        }else if(commentState.getState() == 0){
            moreBt.setClickable(false);
            moreBt.setText(R.string.article_loading_comment);
        }else {
            moreBt.setClickable(true);
            moreBt.setText(R.string.article_no_more_comment);
        }
    }
}